﻿using System;
using System.Net;

namespace Red.Core.Network.PacketNetwork
{
    public abstract class CommAddress
    {
        /// <summary>
        /// Sets protocol specific address values based on uri format
        /// </summary>
        /// <param name="address">Uri formatted string. Exmaple: "127.0.0.1:50", "redEditorPipe" </param>
        public abstract void Set( string address );

        protected Uri GetUri( string address )
        {
            Uri result = new Uri( address );
            return result;
        }
    }

    public class TcpAddress : CommAddress
    {
        public IPEndPoint EndPoint { get; private set; }

        public TcpAddress()
        {
        }

        public TcpAddress( string address )
        {
            Set( address );
        }

        public TcpAddress( Uri uri )
        {
            Set( uri );
        }

        public TcpAddress( IPAddress address, int port )
        {
            if ( port < 0 )
                throw new Exception( "Invalid TCP port: " + port );

            EndPoint = new IPEndPoint( address, port );
        }

        public void Set( Uri uri )
        {
            if ( uri.Port < 0 )
                throw new Exception( "Invalid TCP port: " + uri.Port );

            IPAddress ip = IPAddress.Parse( uri.Host );
            EndPoint = new IPEndPoint( ip, uri.Port );
        }

        public override void Set( string address )
        {
            Uri uri = GetUri( "tcp://" + address );

            Set( uri );
        }
    }

    public class NamedPipeAddress : CommAddress
    {
        public string PipeName { get; private set; }

        public NamedPipeAddress()
        {
        }

        public NamedPipeAddress( string address )
        {
            Set( address );
        }

        public override void Set( string address )
        {
            PipeName = address;
        }
    }
}
